package com.dys.mvvmstudy.viewmodel;

import android.app.Application;
import android.view.View;

import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;

import com.dys.mvvmstudy.BR;
import com.dys.mvvmstudy.bean.Account;
import com.dys.mvvmstudy.callback.MCallBack;
import com.dys.mvvmstudy.databinding.ActivityMvvmBinding;
import com.dys.mvvmstudy.model.MVVMModel;

public class MVVMViewModel extends BaseObservable {

    /**
     * 展示结果
     */
    private String result;

    @Bindable
    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
        // 实现自动更新
        notifyPropertyChanged(BR.result);
    }

    /**
     * 用户输入的账号
     */
    private String userInput;

    @Bindable
    public String getUserInput() {
        return userInput;
    }

    public void setUserInput(String userInput) {
        this.userInput = userInput;
        notifyPropertyChanged(BR.userInput);
    }

    private MVVMModel mvvmModel;
    private ActivityMvvmBinding binding;


    public MVVMViewModel() {}

    /**
     * 一般需要传入application对象，方便在ViewModel中使用application,比如需要使用sharedpreferences
     * @param application 全局对象
     */
    public MVVMViewModel(Application application, ActivityMvvmBinding binding) {
        mvvmModel = new MVVMModel();
        this.binding= binding;
    }

    /**
     * 获取数据
     * @param view 视图对象
     */
    public void getData(View view){

        mvvmModel.getAccountData(userInput, new MCallBack() {
            @Override
            public void onSuccess(Account account) {

                String info = account.getName() + " | " + account.getLevel();
                setResult(info);

            }

            @Override
            public void onFailure() {
                setResult("获取数据失败！");
            }
        });
    }
}
